package com.example.mvvmdemo.http;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.NetworkUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.example.mvvmdemo.AppConstants;
import com.example.mvvmdemo.http.HttpStatus;

import org.json.JSONObject;

import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;

import io.reactivex.rxjava3.annotations.NonNull;
import io.reactivex.rxjava3.internal.observers.BlockingBaseObserver;
import okhttp3.ResponseBody;
import retrofit2.HttpException;

public abstract class BaseObserver<T> extends BlockingBaseObserver<T> {


    @Override
    public void onNext(@NonNull T t) {
        LogUtils.d(t);
    }

    @Override
    public void onError(@NonNull Throwable e) {
        LogUtils.e(e.getMessage());
        e.printStackTrace();
        String error = onErrorMsgWith401(e);
        ToastUtils.showLong(error);
    }


    protected String onErrorMsgWith401(Throwable e) {
        if (e instanceof HttpException) {
            HttpException he = (HttpException) e;
            if (he.code() == HttpStatus.SC_UNAUTHORIZED) {
//                ActivityUtils.startActivity(LoginActivity.class);
//                ActivityUtils.finishAllActivities();
            }
        }
        return onErrorMsg(e);
    }

    protected String onErrorMsg(Throwable e) {
        String error = "未知错误";
        if (e instanceof HttpException) {
            ResponseBody body = ((HttpException) e).response().errorBody();
            try {
                JSONObject o = new JSONObject(body != null ? body.string() : null);
                error = o.optString("error");
            } catch (Exception e1) {
                e1.printStackTrace();
                error = "服务器开小差了";
            }
        } else if (e instanceof UnknownHostException) {
            if (!NetworkUtils.isConnected()) {
                error = "无网络连接";
            } else if (!NetworkUtils.isAvailableByPing(AppConstants.API_BASEURL)) {
                error = "无法连接服务器";
            }
        } else if (e instanceof SocketException) {
            error = "连接被意外中断";
        } else if(e instanceof SocketTimeoutException){
            error = "连接超时";
        }
        return error;
    }
}
